// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/

#[macro_use]
extern crate getset;

pub mod app;
pub mod config;
pub mod initialize;

use std::sync::Arc;

use crate::config::config::ApplicationConfig;
use crate::initialize::config::init_config;
use colored::Colorize;
use mf_core::{event::EventHandler, ForgeResult};
use shared::event::Event;
use shared::ContextHelper;
use tauri::{AppHandle, Emitter as _, Runtime};
fn display_banner() {
    let banner = r#"
    
    ██████╗ ██████╗ ██╗ ██████╗███████╗
    ██╔══██╗██╔══██╗██║██╔════╝██╔════╝
    ██████╔╝██████╔╝██║██║     █████╗  
    ██╔═══╝ ██╔══██╗██║██║     ██╔══╝  
    ██║     ██║  ██║██║╚██████╗███████╗
    ╚═╝     ╚═╝  ╚═╝╚═╝ ╚═════╝╚══════╝
    "#;

    let lines: Vec<&str> = banner.lines().collect();
    for (i, line) in lines.iter().enumerate() {
        if i < 2 {
            println!("{}", line.bright_blue());
        } else if i < 4 {
            println!("{}", line.bright_cyan());
        } else if i < 6 {
            println!("{}", line.bright_green());
        } else if i < 8 {
            println!("{}", line.bright_yellow());
        } else {
            println!("{}", line.bright_magenta());
        }
    }
}

/// 项目启动 准备工作
pub async fn init_context() -> anyhow::Result<()> {
    display_banner();
    let _ = init_config().await;
    Ok(())
}

pub fn get_config() -> &'static ApplicationConfig {
    ContextHelper::get::<ApplicationConfig>()
}
pub fn init_event_handler<R: Runtime>(app: AppHandle<R>) {
    let event_bus = ContextHelper::get_event_bus();
    let event_handler = DefaultEventHandler { app: app.clone() };
    let _ = event_bus.write().unwrap().add_event_handler(Arc::new(event_handler));
}

#[derive(Debug)]
pub struct DefaultEventHandler<R: Runtime> {
    app: AppHandle<R>,
}
#[async_trait::async_trait]
impl<R: Runtime> EventHandler<Event> for DefaultEventHandler<R> {
    async fn handle(
        &self,
        event: &Event,
    ) -> ForgeResult<()> {
        if event.0.starts_with("emit:") {
            // 冒号分割 获取事件名
            let parts: Vec<&str> = event.0.split(':').collect();
            let command = parts[1];
            let info = event.1.clone();
            let _ = self.app.emit(&command, info);
        }
        Ok(())
    }
}
